<template>
	<div class="patient-prescription">
		<el-card class="main-card">
			<div slot="header" class="card-header">
				<span class="title">我的处方记录</span>
				<div class="header-actions">
					<!-- 筛选条件 -->
					<div class="filter-container">
						<el-checkbox-group v-model="filterStatus" @change="handleFilterChange">
							<el-checkbox label="pending" border>待审核</el-checkbox>
							<el-checkbox label="verified" border>已审核</el-checkbox>
							<el-checkbox label="completed" border>已完成</el-checkbox>
							<el-checkbox label="cancelled" border>已取消</el-checkbox>
						</el-checkbox-group>

						<el-switch v-model="hideExpired" active-text="隐藏已超时" inactive-text="显示已超时"
							@change="handleExpiredChange" style="margin-left: 20px;" />

						<el-button type="primary" size="small" @click="refreshList" style="margin-left: 20px;">
							<i class="el-icon-refresh"></i> 刷新
						</el-button>
					</div>
				</div>
			</div>

			<!-- 处方列表 -->
			<div class="prescription-list" v-loading="loading">
				<!-- 空状态 -->
				<el-empty v-if="filteredList.length === 0" :description="getEmptyDescription" :image-size="200">
					<el-button type="primary" @click="resetFilters">重置筛选条件</el-button>
				</el-empty>

				<!-- 处方卡片 -->
				<div v-else class="prescription-cards">
					<el-card v-for="prescription in filteredList" :key="prescription.orderId" class="prescription-card"
						:class="getStatusClass(prescription.orderStatus)">
						<div slot="header" class="prescription-header">
							<div class="header-left">
								<span class="order-id">处方ID: {{ prescription.orderId }}</span>
								<el-tag :type="getOrderTypeTag(prescription.orderType)" size="small" class="type-tag">
									{{ prescription.orderType === 'drug' ? '药品处方' : '检查处方' }}
								</el-tag>
								<el-tag :type="getStatusTag(prescription.orderStatus)" size="small" class="status-tag">
									{{ getStatusText(prescription.orderStatus) }}
								</el-tag>

								<!-- 超时标识 -->
								<el-tag v-if="isExpired(prescription)" type="danger" size="small" class="expired-tag">
									已超时
								</el-tag>
							</div>
							<span class="visit-id">诊疗号: {{ prescription.visitId }}</span>
						</div>

						<!-- 药品处方详情 -->
						<div v-if="prescription.orderType === 'drug'" class="drug-details">
							<div class="drug-info">
								<div class="drug-name">
									<strong>{{ prescription.orderContent }}</strong>
									<span class="drug-spec">{{ prescription.drugSpec }}</span>
								</div>

								<div class="usage-details">
									<div class="detail-item">
										<span class="label">用法用量:</span>
										<span
											class="value">{{ prescription.dosage }}{{ prescription.dosageUnit }}</span>
									</div>
									<div class="detail-item">
										<span class="label">使用频次:</span>
										<span class="value">{{ prescription.frequency }}</span>
									</div>
									<div class="detail-item">
										<span class="label">给药途径:</span>
										<span class="value">{{ prescription.administrationRoute }}</span>
									</div>
								</div>
							</div>
						</div>

						<!-- 检查处方详情 -->
						<div v-else class="exam-details">
							<div class="exam-info">
								<div class="exam-name">
									<strong>{{ prescription.orderContent }}</strong>
								</div>

								<div class="exam-details">
									<div class="detail-item">
										<span class="label">紧急程度:</span>
										<el-tag :type="getEmergencyTag(prescription.frequency)" size="small">
											{{ prescription.frequency }}
										</el-tag>
									</div>
								</div>
							</div>
						</div>

						<!-- 时间信息 -->
						<div class="time-info">
							<div class="time-row">
								<div class="time-item">
									<span class="label">开始时间:</span>
									<span class="value">{{ formatDateTime(prescription.startTime) }}</span>
								</div>
								<div class="time-item" v-if="prescription.endTime">
									<span class="label">结束时间:</span>
									<span class="value">{{ formatDateTime(prescription.endTime) }}</span>
								</div>
							</div>
							<div class="time-item">
								<span class="label">开具时间:</span>
								<span class="value">{{ formatDateTime(prescription.createdTime) }}</span>
							</div>
						</div>

						<!-- 底部信息 -->
						<div class="footer-info">
							<div class="doctor-info">
								<span class="label">开具医生:</span>
								<span class="value">{{ prescription.doctorName || '医生信息' }}</span>
							</div>
							<div class="order-code">
								<span class="label">药品编码:</span>
								<span class="value">{{ prescription.drugCode || 'N/A' }}</span>
							</div>
						</div>
					</el-card>
				</div>
			</div>

			<!-- 底部统计信息 -->
			<div class="statistics-footer" v-if="filteredList.length > 0">
				<span class="stat-item">
					<i class="el-icon-document"></i>
					共 {{ filteredList.length }} 条处方
				</span>
				<span class="stat-item">
					<i class="el-icon-medicine-box"></i>
					药品处方: {{ drugCount }}
				</span>
				<span class="stat-item">
					<i class="el-icon-search"></i>
					检查处方: {{ examCount }}
				</span>
				<span class="stat-item">
					<i class="el-icon-time"></i>
					已超时: {{ expiredCount }}
				</span>
			</div>
		</el-card>
	</div>
</template>

<script>
	import http from '../../utils/request.js'

	export default {
		data() {
			return {
				loading: false,
				myPrescriptionList: [],
				filterStatus: ['pending', 'verified', 'completed', 'cancelled'], // 默认显示所有状态
				hideExpired: false // 默认不隐藏已超时
			}
		},
		async created() {
			await this.getMyPrescriptionList();
		},
		computed: {
			// 过滤后的列表
			filteredList() {
				let filtered = this.myPrescriptionList;

				// 状态筛选
				if (this.filterStatus.length > 0) {
					filtered = filtered.filter(item => this.filterStatus.includes(item.orderStatus));
				}

				// 超时筛选
				if (this.hideExpired) {
					filtered = filtered.filter(item => !this.isExpired(item));
				}

				// 按时间倒序排列（最新的在前面）
				return filtered.sort((a, b) => {
					return new Date(b.createdTime) - new Date(a.createdTime);
				});
			},

			// 药品处方数量
			drugCount() {
				return this.filteredList.filter(item => item.orderType === 'drug').length;
			},

			// 检查处方数量
			examCount() {
				return this.filteredList.filter(item => item.orderType === 'exam').length;
			},

			// 已超时数量
			expiredCount() {
				return this.filteredList.filter(item => this.isExpired(item)).length;
			},

			// 空状态描述
			getEmptyDescription() {
				if (this.myPrescriptionList.length === 0) {
					return '暂无处方记录';
				} else {
					return '暂无符合条件的处方记录';
				}
			}
		},
		methods: {
			async getMyPrescriptionList() {
				this.loading = true;
				try {
					const resp = await http.get('/patient/getMyPrescription', {
						headers: {
							userId: this.$store.state.user.id
						}
					});
					if (resp.data.code === 1) {
						this.myPrescriptionList = resp.data.data || [];
					} else {
						this.$message.error(resp.data.msg || '获取处方列表失败');
					}
				} catch (error) {
					console.error('获取处方列表失败:', error);
					this.$message.error('获取处方列表失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			},

			// 刷新列表
			async refreshList() {
				await this.getMyPrescriptionList();
				this.$message.success('刷新成功');
			},

			// 检查是否已超时
			isExpired(prescription) {
				if (!prescription.endTime) return false;

				const endTime = new Date(prescription.endTime);
				const now = new Date();
				return endTime < now;
			},

			// 格式化时间
			formatDateTime(dateTime) {
				if (!dateTime) return '--';
				return dateTime.replace('T', ' ').substring(0, 16);
			},

			// 获取处方类型标签样式
			getOrderTypeTag(type) {
				return type === 'drug' ? 'success' : 'primary';
			},

			// 获取状态标签样式
			getStatusTag(status) {
				const statusMap = {
					'pending': 'warning',
					'verified': 'success',
					'completed': 'info',
					'cancelled': 'danger'
				};
				return statusMap[status] || 'info';
			},

			// 获取状态文本
			getStatusText(status) {
				const statusTextMap = {
					'pending': '待审核',
					'verified': '已审核',
					'completed': '已完成',
					'cancelled': '已取消'
				};
				return statusTextMap[status] || status;
			},

			// 获取紧急程度标签样式
			getEmergencyTag(emergency) {
				const emergencyMap = {
					'立即': 'danger',
					'紧急': 'warning',
					'常规': 'info'
				};
				return emergencyMap[emergency] || 'info';
			},

			// 获取卡片状态类名
			getStatusClass(status) {
				const classMap = {
					'pending': 'status-pending',
					'verified': 'status-verified',
					'completed': 'status-completed',
					'cancelled': 'status-cancelled'
				};
				return classMap[status] || '';
			},

			// 筛选条件变化
			handleFilterChange() {
				console.log('筛选状态:', this.filterStatus);
			},

			// 超时筛选变化
			handleExpiredChange() {
				console.log('隐藏已超时:', this.hideExpired);
			},

			// 重置筛选条件
			resetFilters() {
				this.filterStatus = ['pending', 'verified', 'completed', 'cancelled'];
				this.hideExpired = false;
				this.$message.success('筛选条件已重置');
			}
		}
	}
</script>

<style scoped>
	.patient-prescription {
		padding: 20px;
		background-color: #f5f7fa;
		min-height: calc(100vh - 84px);
	}

	.main-card {
		border-radius: 8px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.card-header {
		display: flex;
		flex-direction: column;
		gap: 15px;
		padding: 15px 20px;
	}

	.title {
		font-size: 18px;
		font-weight: 600;
		color: #303133;
	}

	.header-actions {
		display: flex;
		align-items: center;
	}

	.filter-container {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 10px;
		width: 100%;
	}

	.el-checkbox-group {
		display: flex;
		gap: 10px;
		flex-wrap: wrap;
	}

	.el-checkbox.is-bordered {
		margin-right: 0 !important;
	}

	.prescription-list {
		min-height: 300px;
	}

	.prescription-cards {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.prescription-card {
		border-radius: 8px;
		transition: all 0.3s ease;
		border-left: 4px solid #409EFF;
	}

	.prescription-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
	}

	.prescription-card.status-pending {
		border-left-color: #E6A23C;
	}

	.prescription-card.status-verified {
		border-left-color: #67C23A;
	}

	.prescription-card.status-completed {
		border-left-color: #909399;
	}

	.prescription-card.status-cancelled {
		border-left-color: #F56C6C;
	}

	.prescription-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 20px;
		background-color: #f8f9fa;
		border-bottom: 1px solid #ebeef5;
	}

	.header-left {
		display: flex;
		align-items: center;
		gap: 10px;
		flex-wrap: wrap;
	}

	.order-id {
		font-weight: 600;
		color: #606266;
	}

	.type-tag,
	.status-tag,
	.expired-tag {
		font-weight: 500;
	}

	.visit-id {
		color: #909399;
		font-size: 14px;
	}

	.drug-details,
	.exam-details {
		padding: 20px;
	}

	.drug-info,
	.exam-info {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.drug-name,
	.exam-name {
		display: flex;
		align-items: center;
		gap: 12px;
		font-size: 16px;
	}

	.drug-name strong {
		color: #303133;
		font-size: 18px;
	}

	.drug-spec {
		background-color: #f0f9ff;
		color: #409EFF;
		padding: 2px 8px;
		border-radius: 4px;
		font-size: 14px;
	}

	.usage-details,
	.exam-details {
		display: flex;
		flex-wrap: wrap;
		gap: 24px;
	}

	.detail-item {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.detail-item .label {
		color: #909399;
		font-size: 14px;
		min-width: 70px;
	}

	.detail-item .value {
		color: #606266;
		font-weight: 500;
	}

	.time-info {
		padding: 16px 20px;
		background-color: #f8f9fa;
		border-top: 1px solid #ebeef5;
		border-bottom: 1px solid #ebeef5;
	}

	.time-row {
		display: flex;
		gap: 40px;
		margin-bottom: 12px;
	}

	.time-item {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.time-item .label {
		color: #909399;
		font-size: 14px;
		min-width: 70px;
	}

	.time-item .value {
		color: #606266;
		font-weight: 500;
	}

	.footer-info {
		padding: 16px 20px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.doctor-info,
	.order-code {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.footer-info .label {
		color: #909399;
		font-size: 14px;
	}

	.footer-info .value {
		color: #606266;
		font-weight: 500;
	}

	/* 底部统计信息 */
	.statistics-footer {
		margin-top: 20px;
		padding: 15px 20px;
		background-color: #f8f9fa;
		border-top: 1px solid #ebeef5;
		display: flex;
		justify-content: flex-start;
		gap: 30px;
		flex-wrap: wrap;
	}

	.stat-item {
		display: flex;
		align-items: center;
		gap: 8px;
		color: #606266;
		font-size: 14px;
	}

	.stat-item i {
		color: #409EFF;
		font-size: 16px;
	}

	/* 响应式设计 */
	@media screen and (max-width: 768px) {
		.patient-prescription {
			padding: 10px;
		}

		.card-header {
			gap: 10px;
		}

		.filter-container {
			flex-direction: column;
			align-items: flex-start;
		}

		.prescription-header {
			flex-direction: column;
			align-items: flex-start;
			gap: 8px;
		}

		.time-row {
			flex-direction: column;
			gap: 12px;
		}

		.footer-info {
			flex-direction: column;
			align-items: flex-start;
			gap: 12px;
		}

		.usage-details {
			flex-direction: column;
			gap: 12px;
		}

		.detail-item {
			width: 100%;
		}

		.statistics-footer {
			flex-direction: column;
			gap: 10px;
		}
	}

	/* 筛选器样式 */
	::v-deep .el-checkbox.is-bordered {
		margin-right: 0;
		margin-bottom: 5px;
	}

	::v-deep .el-checkbox-group {
		margin-bottom: 0;
	}
</style>